<?php
/**
 * 商品分类
 *
 */
class Goodscat extends MyBase{
	private static $categorys = array();
	
	function __construct() {
		parent::__construct('goods_category.id', array('name' => 'name', 'mark' => 'mark'));
	}
		
	/**
	 * 修改商品分类
	 */
	public function edit($post){
		$id = empty($post['id']) ? 0 : intval($post['id']);
		$select = array(
			'pid'	=> $post['pid'],
			'mark'	=> $post['mark'],
		);
		if($id > 0){
			$select['kept'] = " AND id!={$id}";
		}
		$rs = $this->db->get_row($this->tbname, $select, 'id');
		if(!empty($rs)) {
			return lang('already').lang('exist');
		}
		if(empty($post['spec_multi']))$post['spec_multi'] = array();
		if(empty($post['spec_empty']))$post['spec_empty'] = array();
		if(empty($post['spec_item']))$post['spec_item'] = array();
		$post['attr'] = empty($post['attr_rank']) ? serialize(array()) : $this->format_prototype_attr($post['attr_rank'], $post['attr_input'], $post['attr_prompt'], $post['attr_regexp']);
		$post['spec'] = empty($post['spec_rank']) ? serialize(array()) : $this->format_prototype_spec($post['spec_rank'], $post['spec_item'], $post['spec_prompt'], $post['spec_regexp'], $post['spec_multi'], $post['spec_empty']);
		$post['range'] = $this->format_range_in($post['range']);
		$data = array(
			'pid'		=> $post['pid'],
			'name'		=> $post['name'],
			'mark'		=> $post['mark'],
			'range'		=> $post['range'],
			'show'		=> $post['show'] == 0 ? 0 : 1,
			'rank'		=> $post['rank'],
			'memo'		=> $post['memo'],
			'attr'		=> $post['attr'],
			'spec'		=> $post['spec'],
			'brand'		=> $post['brand'],
		);
		$oUpload = new Upload(array(
			'upload_form_field'	=> 'picpath',
			'auto_date_dir'		=> true,
			'out_file_dir'		=> UP_PTH.'gcat/',
			'allowed_file_ext'	=> array('gif', 'jpg', 'jpeg', 'png'),
		));
		$img_arr = $oUpload->upload_process();
		if(!empty($img_arr)){

			if(isset($post['picpath']) && !empty($post['picpath'])){	// 删除旧图
				@unlink(UP_PTH.$post['picpath']);
				@unlink(UP_PTH.'thumb/'.$post['picpath']);
			}
			$img_path = array_pop($img_arr);			
			File::resize($img_path, 200, 150, 'adaptive');	// 缩小至合适大小、截取
			$data['picpath'] = str_replace(UP_PTH, '', $img_path);
		}
		if($id > 0){
			$data['updatetime'] = TIME;
			$r = $this->db->update($this->tbname, array('id' => $id), $data);
		}else{
			$data['addtime'] = TIME;
			$r = $id = $this->db->insert($this->tbname, $data);
		}
		if($r > 0){
			return $this->cache_category();
		}
		return $r;
	}
	
	public function format_prototype_attr($checks, $defaults, $prompts, $regexps){
		//$prototypes = Prototype::get_prototypes();
		$arr = array();
		if(empty($checks)){
			return serialize($arr);
		}
		asort($checks);
		foreach($checks as $prototypeid => $rank){
			//$prototype_info = $prototypes[$prototypeid];
			$arr[$prototypeid] = array(
				'id'		=> $prototypeid,
				'default'	=> empty($defaults[$prototypeid]) ? '' : trim($defaults[$prototypeid]),
				'prompt'	=> $prompts[$prototypeid],
				'regexp'	=> stripslashes($regexps[$prototypeid]),
			);
		}
		return serialize($arr);
	}
	
	public function format_prototype_spec($checks, $items, $prompts, $regexps, $spec_multi = array(), $spec_empty = array()){
		//$prototypes = Prototype::get_prototypes();
		$arr = array();
		if(empty($checks) || empty($items)){
			return serialize($arr);
		}
		asort($checks);
		foreach($checks as $prototypeid => $rank){
			//$prototype_info = $prototypes[$prototypeid];
			$arr[$prototypeid] = array(
				'id'		=> $prototypeid,
				'item'		=> $items[$prototypeid],
				'prompt'	=> $prompts[$prototypeid],
				'regexp'	=> stripslashes($regexps[$prototypeid]),
				'multi'		=> empty($spec_multi[$prototypeid]) ? 0 : 1,
				'empty'		=> empty($spec_empty[$prototypeid]) ? 0 : 1,
			);
		}
		return serialize($arr);
	}

	public function format_range_in($range){
		$range = str_replace(array(' ', '　'), '', $range);
		$range = str_replace(array('，', '；'), ',', $range);
		$_arr = explode(',', $range);
		$arr = array();
		$limitless = '';
		foreach ($_arr as $val) {
			$val = trim($val);
			if($val === '')continue;
			if($val == '~'){
				$limitless = '~';
				continue;
			}
			$arr[] = intval($val);
		}
		asort($arr);
		if(!empty($limitless)){
			$arr[] = $limitless;
		}
		return implode(',', $arr);
	}

	public function format_range_out($range){
		if(empty($range))return array();
		$_arr = explode(',', $range);
		$arr = array();
		$tmp = array();
		for($i = 0; $i < count($_arr); ){
			if(empty($tmp)){
				$tmp[] = $_arr[$i];
				$i ++;
			}else{
				if($_arr[$i] == '~'){
					$tmp[] = '~';
					$i ++;
				}else{
					$tmp[] = ''.($_arr[$i] - 1);
				}
				$arr[] = $tmp;
				$tmp = array();
			}
		}
		
		return $arr;
	}
	
	// 更新排序与显示开关，及淘宝编号
	public function rank($post){
		if(!is_array($post['rank']))return false;
		if(!is_array($post['show']))$post['show'] = array($post['show']);
		$iRtn = 0;
		foreach($post['rank'] as $id => $rank){
			$data = array(
				'rank'		 => $rank, 
				'updatetime' => TIME,
			);
			if(isset($post['show'][$id])){
				$data['show'] = 1;
			}else{
				$data['show'] = 0;
			}
			if($this->db->update($this->tbname, array('id' => $id), $data)){
				$iRtn ++;
			}
		}
		if($iRtn > 0){
			return $this->cache_category();
		}else{
			return $iRtn;
		}
	}
			
	/**
	 * 删除商品分类
	 */
	public function del($post){
		if(!is_array($post['list'])) {
			$post['list'] = array($post['list']);
		}
		$iRtn = 0;
		foreach($post['list'] as $id){
			$sublist = $this->db->sql_row("SELECT * FROM `{$this->tbname}` WHERE `pid`=$id");
			if(!empty($sublist)){
				continue;
			}
			if($this->db->delete($this->tbname, array('id' => $id))){
				$iRtn ++;
			}
		}
		if($iRtn > 0){
			return $this->cache_category();
		}
		return $iRtn;
	}
	
	/**
	 * 取一条记录
	 */
	/*public function get_row($id, $fields = '*'){
		$select = array('id' => $id);
		return $this->db->get_row($this->tbname, $select, $fields);
	}*/
	
	/**
	 * 取列表
	 */
	/*public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET){
		$select['kept'] = '';
		if(!empty($select['name'])){
			$select['kept'] .= " AND `name` LIKE '%{$select['name']}%'";
			unset($select['name']);
		}
		if(!empty($select['mark'])){
			$select['kept'] .= " AND `mark` LIKE '%{$select['mark']}%'";
			unset($select['mark']);
		}
		return $this->db->get_list($this->tbname, $fields, $select, $order, $page, $size, $offset);
	}*/
	
	/********************************************************************************
	 * 取菜单树
	 ********************************************************************************/
	
	public function get_category_list($pid = 0, $path = '', $level = 0, $depth = 0){
		if($pid > 0)$path = trim($path.','.$pid, ', ');
		$arr = array();
		//$where = empty($keyword) ? '' : " AND (name LIKE '%$keyword%' OR mark LIKE '%$keyword%')";
		$list = $this->db->sql_all("SELECT * FROM `{$this->tbname}` WHERE `pid`={$pid} ORDER BY `rank` DESC,`id` ASC");
		if(isset($list['list']) && !empty($list['list'])){
			foreach($list['list'] as $row){
				$row['path'] = $path;
				$row['level'] = $level;
				$row['range'] = $this->format_range_out($row['range']);
				if($row['mark'] == '')$row['mark'] = $row['id'];
				$arr[$row['id']] = $row;
				$next_level = $level + 1;
				if($depth == 0 || $next_level < $depth){
					$_arr = $this->get_category_list($row['id'], $path, $next_level, $depth);
					if(!empty($_arr)){
						foreach($_arr as $catid => $row){
							$arr[$catid] = $row;
						}
					}
				}
			}
		}
		return $arr;
	}
	
	// 仅子类（子类的子类）
	public function get_category_list_children(&$arr = array(), $pid = 0){
		$ids = $this->db->sql_cols("SELECT `id` FROM `{$this->tbname}` WHERE `pid`={$pid} ORDER BY `rank` DESC,`id` ASC", 'id');
		if(empty($ids)){
			$arr[] = $pid;
		}else{
			foreach($ids as $catid){
				$this->get_category_list_children($arr, $catid);
			}
		}
		return $arr;
	}
	
	public function get_category_tree_ul($pid = 0, $except_id = 0, $level = 99){
		$categorys = array();
		if($pid == 0){
			$categorys[] = '<li><a href="#" onClick="set_category_id(this, 0);return false;">根</a><ul>';
		}
		$list = $this->db->sql_all("SELECT * FROM `{$this->tbname}` WHERE `pid`={$pid} ORDER BY `rank` DESC,`id` ASC");
		if(isset($list['list']) && !empty($list['list'])){
			foreach($list['list'] as $row){
				$sub_categorys = $this->get_category_tree_ul($row['id'], $except_id, $level + 1);
				if(!empty($sub_categorys)){
					$categorys[] = '<li><a href="#" onClick="set_category_id(this,'.$row['id'].');return false;">'.$row['name'].'</a>';
					
					$categorys[] = '<ul>';
					// $categorys[] = '<li class="topline"></li>';
					$categorys[] = $sub_categorys;
					$categorys[] = '</ul></li>';
				}else{
					$categorys[] = '<li><a href="#" onClick="set_category_id(this,'.$row['id'].');return false;">'.$row['name'].'</a></li>';
				}
				
			}
		}
		
		if($pid == 0){
			$categorys[] = '</ul></li>';
		}
		return implode("\n", $categorys);
	}
	
	public function get_category_tree($pid = 0, $except_id = 0, $path = '', $level = 0){
		if($pid > 0)$path = trim($path.','.$pid, ', ');
		$categorys = array();
		$list = $this->db->sql_all("SELECT * FROM `{$this->tbname}` WHERE `pid`={$pid} ORDER BY `rank` DESC,`id` ASC");
		if(isset($list['list']) && !empty($list['list'])){
			foreach($list['list'] as $row){
				$row['path'] = $path;
				$row['level'] = $level;
				$row['range'] = $this->format_range_out($row['range']);
				$sub_categorys = $this->get_category_tree($row['id'], $except_id, $path, $level + 1);
				if(!empty($sub_categorys)){
					$row['categorys'] = $sub_categorys;
				}
				$categorys[$row['id']] = $row;			
			}
		}
		return $categorys;
	}	
	
	/********************************************************************************
	 * 缓存
	 ********************************************************************************/
	
	public function cache_category(){
		$category_list = $this->get_category_list();
		$category_tree = $this->get_category_tree();
		$category_mark_id_list = array();
		$category_id_name_list = array();
		//$category_taobaoid_id_list = array();
		foreach($category_list as $category_id => $category_info){
			$category_info['attr'] = @unserialize($category_info['attr']);
			$category_info['spec'] = @unserialize($category_info['spec']);
			$category_mark_id_list[$category_info['mark']] = $category_id;
			$category_id_name_list[$category_id] = $category_info['name'];
			//if(empty($category_info['taobaoid']))continue;
			//$category_taobaoid_id_list[$category_info['taobaoid']] = $category_id;
			$category_list[$category_id] = $category_info;
		}
		$r = cache_write('goods_categorys.php', array('category_list' => $category_list, 'category_tree' => $category_tree, 'category_mark_id_list' => $category_mark_id_list, 'category_id_name_list' => $category_id_name_list/*, 'category_taobaoid_id_list' => $category_taobaoid_id_list*/));
		if($r > 0){
			cache_delete('goods_child_category.php');
			return 1;
		}else{
			return -1;
		}
	}

	// 读取分类信息
	public static function get_category($catid = 0, $field = '', $parents = false){
		if(empty(self::$categorys)){
			self::$categorys = cache_read('goods_categorys.php');
		}
		if(!empty($catid)){
			switch ($catid) {
				case 'list':
					return self::$categorys['category_list'];
					break;
				case 'tree':
					return self::$categorys['category_tree'];
					break;
				case 'mark':
					return self::$categorys['category_mark_id_list'];
					break;
				case 'name':
					return self::$categorys['category_id_name_list'];
					break;
			}
			$category = self::$categorys['category_list'][$catid];
			if($field != '' && isset($category[$field])){
				if(empty($category[$field]) && $parents == true && !empty($category['path'])){
					$path_arr = explode(',', $category['path']);
					for($i = count($path_arr) - 1; $i >= 0; $i--){
						$pid = $path_arr[$i];
						$category = self::$categorys['category_list'][$pid];
						if(!empty($category[$field])){
							return $category[$field];
						}
					}					
				}
				return $category[$field];
			}
			return $category;
		}
		return self::$categorys;
	}

	public static function get_category_by_mark($mark, $field = ''){
		$categorys = self::get_category();
		if(array_key_exists($mark, $categorys['category_mark_id_list'])){
			$_catid = $categorys['category_mark_id_list'][$mark];
			$category = $categorys['category_list'][$_catid];
			if($field != '' && isset($category[$field])){
				return $category[$field];
			}
			return $category;
		}
		return false;
	}

	public static function get_child_categorys($catid){
		$child_category_arr = cache_read('goods_child_category.php');
		if(empty($child_category_arr)){
			$child_category_arr = array();
		}
		if(!isset($child_category_arr[$catid])){
			$oGoodscat = & Goodscat::instance();
			$child_category_arr[$catid] = $oGoodscat->get_category_list_children($childs, $catid);
			cache_write('goods_child_category.php', $child_category_arr);
		}
		return $child_category_arr[$catid];
	}
}
?>